<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/11 16:24
 * Desc: 游记
 */
class Service_Api_Notes extends Contract_Api_Notes
{

    /**
     * 类型id
     */
    const TYPE_ID = 101;

    public function get_list($params): array
    {

        $list = Model_Api_V2_Notes::search($params);
        foreach ($list as &$item) {

            if (empty($item['litpic'])) {
                $item['litpic'] = $item['bannerpic'];
            }

            if (empty($item['description'])) {
                $item['description'] = strip_tags($item['content']);
            }
            //匹配正文内容是否是PC编辑的
            if (preg_match('/<p.*?>.*?<\/p>/m', $item['content'], $match)) {
                $item['is_pc'] = 1;
            }

            $item['favorite'] += $item['virtual_favorite'];
            $item['shownum']  = $item['nums'];

            $item['litpic'] = $this->img_url($item['litpic'], 750, 400);
            $item['title']  = Common::cutstr_html($item['title'], 40);

            $item['addtime'] = date("Y-m-d", $item['addtime']);

            $item['member'] = '';
            if ($item['memberid']) {
                $member = Model_Member::get_member_info($item['memberid']);
                if ($member) {
                    $item['member'] = array(
                        'nickname' => $member['nickname'],
                        'litpic' => $this->img_url($member['litpic'], 200, 200)
                    );
                }
            }

            unset($item['memberid']);
        }

        return $list;
    }

    public function get_detail($id): array
    {
        $detail = DB::select(
            'title', 'content', 'litpic', 'shownum', 'description', 'addtime', 'memberid',
            'favorite', 'virtual_favorite', 'read_num', 'video', 'audio'
        )
            ->from('notes')
            ->where('id', '=', $id)
            ->execute()
            ->current();

        if (!$detail) {
            throw new Exception('查询游记失败');
        }

        //点击率加一
        Product::update_click_rate($id, self::TYPE_ID);

        $detail['litpic']  = $this->img_url($detail['litpic'], 750, 400);
        $detail['content'] = $this->content_add_domain($detail['content']);
        $detail['addtime'] = date('Y-m-d H:i:s', $detail['addtime']);

        $detail['member'] = '';
        if ($detail['memberid']) {
            $member = Model_Member::get_member_info($detail['memberid']);
            if ($member) {
                $detail['member'] = array(
                    'nickname' => $member['nickname'],
                    'litpic' => $this->img_url($member['litpic'], 200, 200)
                );
            }
        }

        $detail['commentNum'] = Model_Comment::get_comment_num($id, self::TYPE_ID);
        $detail['shownum']    = $detail['read_num'] ? ($detail['shownum'] + $detail['read_num']) : $detail['shownum'];
        $detail['favorite']   = $detail['virtual_favorite'] ? ($detail['favorite'] + $detail['virtual_favorite']) : $detail['favorite'];
        $detail['summary']    = mb_substr(strip_tags($detail['content']), 0, 40);
        list($video_path, $name) = explode('|', $detail['video']);
        $detail['video_path'] = Model_Api_V2_System::reorganized_resource_url($video_path);

        list($audio_path, $name) = explode('|', $detail['audio']);
        $detail['audio_path'] = Model_Api_V2_System::reorganized_resource_url($audio_path);


        //今日推荐
        $recommend = array();
        if (St_Functions::is_normal_app_install('product_seeding')) {
            $seed = DB::select()
                ->from('product_seeding')
                ->where('id', '=', 3)
                ->and_where('status', '=', 1)
                ->execute()
                ->current();

            if ($seed && $seed['typeid']) {
                $detail['recommend_type_id'] = $seed['typeid'];
                $recommend                   = Model_Api_V2_Product_Seeding::recommend($seed);
                foreach ($recommend as &$item) {
                    $item['litpic'] = $this->img_url($item['litpic'], 750, 400);
                }
            }
        }
        $detail['recommend'] = $recommend;

        unset($detail['memberid']);

        return $detail;
    }

    public function member_notes($mid, $params): array
    {
        /**
         * @var $page
         * @var $pagesize
         */
        extract($params);

        $offset = St_Page::offset($page, $pagesize);

        $list = DB::select(
            'title', 'id', 'litpic', 'shownum', 'favorite', 'addtime', 'memberid',
            'status', 'reason', 'description', 'content'
        )
            ->from('notes')->where('memberid', '=', $mid)
            ->offset($offset)
            ->limit($pagesize)
            ->order_by('addtime', 'desc')
            ->execute()
            ->as_array();

        foreach ($list as &$item) {
            $item['addtime'] = date('Y-m-d', $item['addtime']);
            $item['litpic']  = $this->img_url($item['litpic']);
            $item['content'] = mb_substr(strip_tags($item['content']), 0, 100);

            unset($item['memberid']);
        }

        return $list;
    }

    public function thumbs_up($id): bool
    {
        $notes = ORM::factory('notes')
            ->where('id', '=', $id)
            ->and_where('status', '=', 1)
            ->and_where('ishidden', '=', 0)
            ->find();
        if (!$notes->id) {
            throw new Exception('游记不存在');
        }

        $notes->favorite += 1;
        $notes->save();
        if (!$notes->saved()) {
            throw new Exception('保存失败');
        }

        return true;
    }

    public function thumbs_down($id): bool
    {
        $notes = ORM::factory('notes')
            ->where('id', '=', $id)
            ->and_where('status', '=', 1)
            ->and_where('ishidden', '=', 0)
            ->find();
        if (!$notes->id) {
            throw new Exception('游记不存在');
        }

        $notes->favorite -= 1;
        $notes->save();
        if (!$notes->saved()) {
            throw new Exception('保存失败');
        }

        return true;
    }

    public function delete($mid, $id): bool
    {
        $row = DB::delete('notes')
            ->where('id', '=', $id)
            ->and_where('memberid', '=', $mid)
            ->and_where('status', '!=', 1)
            ->execute();
        if (!$row) {
            throw new Exception('删除失败, 游记不存在或状态错误');
        }
        return true;
    }

    public function edit($mid, $params): bool
    {
        $title   = Arr::get($params, 'title');
        $id      = Arr::get($params, 'id', '');
        $litpic  = Arr::get($params, 'litpic', '');
        $content = Arr::get($params, 'content', '');
        $video   = Arr::get($params, 'video', '');
        $audio   = Arr::get($params, 'audio', '');

        $is_new = false; // 是否是新添加的
        if (!empty($id)) {
            $notes = ORM::factory('notes')
                ->where('id', '=', $id)
                ->and_where('memberid', '=', $mid)
                ->find();
            if (!$notes->id) {
                throw new Exception('游记不存在');
            }
        } else {
            $is_new = true;
            $notes = ORM::factory('notes');
            $notes->memberid = $mid;
            $notes->addtime  = time();
        }

        $notes->title     = $title;
        $notes->content   = St_Functions::substr_uploads($content);
        $notes->litpic    = St_Functions::substr_uploads($litpic);
        $notes->video     = $video;
        $notes->audio     = $audio;
        $notes->bannerpic = "/res/images/notes_default_banner.png";
        $notes->modtime   = time();

        $auditType = intval(Model_Sysconfig::get_configs(0, 'cfg_notes_jifen_audit_type', true));
        if ($auditType == 1) {
            //自动审核
            $notes->status = 1;
            $notes->issend = 1;
        }

        $notes->save();
        if(!$notes->saved()) {
            throw new Exception('保存失败');
        }

        if ($auditType == 1 && $is_new) {
            Model_Api_V2_Notes::notes_jifen($mid);
        }

        return true;
    }
}